﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebServer
{
    public class ServerHelper
    {
        HttpListener httpListener = new HttpListener();
        public void Setup(int port = 80)
        {
            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            httpListener.Prefixes.Add(string.Format("http://+:{0}/", port));//如果发送到8080 端口没有被处理，则这里全部受理，+是全部接收
            httpListener.Start();//开启服务

            Receive();//异步接收请求
        }

        private void Receive()
        {
            httpListener.BeginGetContext(new AsyncCallback(EndReceive), null);
        }

        void EndReceive(IAsyncResult ar)
        {
            var context = httpListener.EndGetContext(ar);
            Dispather(context);//解析请求
            Console.WriteLine("Receive");
            Receive();
        }

        RequestHelper RequestHelper;
        ResponseHelper ResponseHelper;
        void Dispather(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
            RequestHelper = new RequestHelper(request);
            ResponseHelper = new ResponseHelper(response);

            // 对相应的请求做出回应
            bool isFileReadSuccess = RequestHelper.DispatchResources(ResponseFile);
            if(!isFileReadSuccess)
            {
                ResponseHelper.End();
            }
        }

        /// <summary>
        /// 对相应的请求做出回应
        /// <para>参数为请求到的文件夹</para>
        /// </summary>
        /// <param name="fs"></param>
        protected virtual void ResponseFile(FileStream fs)
        {
            ResponseHelper.WriteToClient(fs,RequestHelper.FileType);
        }
    }
}
